package com.ysu.yybk.controller;

import com.ysu.yybk.VO.ResultVO;
import com.ysu.yybk.dto.GroupDTO;
import com.ysu.yybk.entity.discuss.Discuss;
import com.ysu.yybk.enums.ResultEnum;
import com.ysu.yybk.exception.YybkException;
import com.ysu.yybk.form.DiscussAddScoreFrom;
import com.ysu.yybk.form.DiscussForm;
import com.ysu.yybk.service.DiscussTeacherService;
import com.ysu.yybk.util.ResultVOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/teacher/discuss")
public class DiscussTeacherController {

    @Autowired
    private DiscussTeacherService service;

    @GetMapping("/list")
    public ResultVO discussList(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                @RequestParam("courseId") String courseId) {
        if (StringUtils.isEmpty(courseId)) {
            throw new YybkException(ResultEnum.PARAM_ERROR);
        }

        List<Discuss> discussList = service.discussList(current, courseId);
        return ResultVOUtil.success(discussList);
    }

    @GetMapping("/groups")
    public ResultVO groupList(@RequestParam(value = "discussId", defaultValue = "-1") Integer discussId) {
        if (discussId == -1) {
            throw new YybkException(ResultEnum.PARAM_ERROR);
        }

        List<GroupDTO> groupDTOList = service.groupList(discussId);
        return ResultVOUtil.success(groupDTOList);
    }

    @PostMapping("/discuss")
    public ResultVO addDiscuss(@Valid DiscussForm discussForm,
                               BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new YybkException(ResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        service.addDiscuss(discussForm);
        return ResultVOUtil.success();
    }

    @PostMapping("/score")
    public ResultVO addScore(@Valid DiscussAddScoreFrom from,
                             BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new YybkException(ResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        service.addScore(from);
        return ResultVOUtil.success();
    }
}
